<template>
  <div class="student-stats-container">
    <n-h3 style="margin: 0 0 16px 0;">👨‍🎓 学生统计分析</n-h3>
    
    <n-radio-group v-model:value="activeTab" name="tabGroup" style="margin-bottom: 20px;">
      <n-radio-button 
        v-for="tab in tabs" 
        :key="tab.value" 
        :value="tab.value"
        :label="tab.label"
      />
    </n-radio-group>
    
    <n-radio-group v-model:value="chartType" name="chartType" style="margin-bottom: 20px;">
      <n-radio-button 
        v-for="type in chartTypes" 
        :key="type.value" 
        :value="type.value"
        :label="type.label"
      />
    </n-radio-group>
    
    <div v-if="loading" style="text-align: center; padding: 50px;">
      <n-spin size="large" />
      <div style="margin-top: 10px; color: #666;">数据加载中...</div>
    </div>
    
    <div v-else class="chart-wrapper">
      <v-chart 
        :option="chartOption" 
        autoresize 
        style="background-color: #ffffff; height: 500px; border-radius: 8px;"
      />
    </div>
    
    <div class="table-area">
      <n-data-table
        :columns="columns"
        :data="tableData"
        :bordered="true"
        style="margin-top: 20px;"
      />
      
      <div class="pagination-wrapper">
        <n-pagination
          v-model:page="pagination.page"
          :page-count="pagination.pageCount"
          :page-size="pagination.pageSize"
          @update:page="handlePageChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { 
  NH3,
  NRadioGroup,
  NRadioButton,
  NDataTable,
  NPagination,
  NSpin
} from 'naive-ui'
import { use } from 'echarts/core'
import { BarChart, LineChart } from 'echarts/charts'
import { 
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  DataZoomComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import VChart from 'vue-echarts'

import { getCollegeGradeStatistics } from "@/api/studentStatistics"

use([
  BarChart,
  LineChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  DataZoomComponent,
  CanvasRenderer
])

// 选项卡配置
const tabs = ref([
  { label: '年级统计', value: 'grade' },
  { label: '学院统计', value: 'college' }
])

const activeTab = ref('grade')

// 图表类型配置
const chartTypes = ref([
  { label: '柱状图', value: 'bar' },
  { label: '折线图', value: 'line' },
  { label: '堆积图', value: 'stack' }
])

const chartType = ref('bar')

// 分页配置
const pagination = ref({
  page: 1,
  pageSize: 5,
  pageCount: 1
})

const handlePageChange = (page) => {
  pagination.value.page = page
}

// 数据加载状态
const loading = ref(false)

// API调用函数
const fetchData = async () => {
  loading.value = true
  try {
    let response
    switch (activeTab.value) {
      case 'college':
        response = await getCollegeGradeStatistics()
        break
      default:
        response = await getCollegeGradeStatistics()
    }
    
    // 处理API返回的数据
    const apiData = response.data.data || []
    rawData.value.college = apiData.map(item => ({
      name: item.college,
      count: item.total,
      grades: item.grades
    }))
    
    // 更新分页
    pagination.value.pageCount = Math.ceil(rawData.value[activeTab.value].length / pagination.value.pageSize)
    if (pagination.value.page > pagination.value.pageCount) {
      pagination.value.page = 1
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    // 可以在这里添加错误提示
  } finally {
    loading.value = false
  }
}

// 监听选项卡变化，重新获取数据
watch(activeTab, () => {
  fetchData()
})

// 初始化数据
onMounted(() => {
  fetchData()
})

// 山东农业大学实际数据规模（作为备用数据）
const rawData = ref({
  grade: [
    { name: '2022级', count: 8560 },
    { name: '2023级', count: 7820 },
    { name: '2024级', count: 7450 },
    { name: '2025级', count: 6980 }
  ],
  college: [
    { name: '农学院', count: 5400 },
    { name: '植物保护学院', count: 3800 },
    { name: '资源与环境学院', count: 3300 },
    { name: '林学院', count: 3100 },
    { name: '园艺科学与工程学院', count: 3070 },
    { name: '动物科技学院', count: 2980 },
    { name: '机械与电子工程学院', count: 3440 },
    { name: '经济管理学院', count: 3140 },
    { name: '食品科学与工程学院', count: 2570 },
    { name: '生命科学学院', count: 2240 },
    { name: '外国语学院', count: 2500 },
    { name: '公共管理学院', count: 2100 },
    { name: '水利土木工程学院', count: 2840 },
    { name: '信息科学与工程学院', count: 3200 },
    { name: '化学与材料科学学院', count: 2260 }
  ]
})

// 表格配置
const columns = ref([
  { title: '名称', key: 'name', width: 120, ellipsis: { tooltip: true } },
  { title: '学生数量', key: 'count', width: 100 },
  { 
    title: '占比', 
    key: 'percentage',
    width: 100,
    render: (row) => `${row.percentage}%`
  }
])

// 计算表格数据
const tableData = computed(() => {
  const data = rawData.value[activeTab.value]
  const total = data.reduce((sum, cur) => sum + cur.count, 0) || 1
  const processed = data.map(item => ({
    name: item.name,
    count: item.count,
    percentage: ((item.count / total) * 100).toFixed(1)
  }))
  
  pagination.value.pageCount = Math.ceil(processed.length / pagination.value.pageSize)
  
  const start = (pagination.value.page - 1) * pagination.value.pageSize
  const end = start + pagination.value.pageSize
  return processed.slice(start, end)
})

// 图表配置
const chartOption = computed(() => {
  const currentData = rawData.value[activeTab.value]
  const title = `${tabs.value.find(t => t.value === activeTab.value).label} - ${chartTypes.value.find(t => t.value === chartType.value).label}`
  
  if (chartType.value === 'line') {
    return getLineOption(currentData, title)
  } else if (chartType.value === 'stack') {
    return getStackOption(currentData, title)
  } else {
    return getBarOption(currentData, title)
  }
})

// 响应式图表配置
const isMobile = ref(window.innerWidth < 768)

const getBaseOption = (data, title) => {
  const itemCount = data.length
  const defaultShow = isMobile.value ? Math.min(5, itemCount) : Math.min(8, itemCount)
  const startValue = 0
  const endValue = defaultShow - 1
  
  return {
    title: {
      text: title,
      left: 'center',
      textStyle: {
        fontSize: isMobile.value ? 14 : 16
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      confine: true
    },
    legend: {
      data: ['学生人数'],
      top: 30,
      itemWidth: isMobile.value ? 12 : 16,
      itemHeight: isMobile.value ? 12 : 16,
      textStyle: {
        fontSize: isMobile.value ? 12 : 14
      }
    },
    grid: {
      left: isMobile.value ? '15%' : '10%',
      right: '5%',
      bottom: isMobile.value ? '25%' : '18%',
      containLabel: true
    },
    dataZoom: [
      {
        type: 'slider',
        show: true,
        xAxisIndex: [0],
        bottom: isMobile.value ? '12%' : '10%',
        height: 20,
        startValue,
        endValue,
        handleSize: 12,
        brushSelect: false,
        zoomLock: false,
        filterMode: 'filter',
        moveOnMouseMove: false,
        moveRate: 0.2,
        preventDefaultMouseMove: true
      },
      {
        type: 'inside',
        xAxisIndex: [0],
        startValue,
        endValue,
        zoomOnMouseWheel: false,
        moveOnMouseMove: true,
        moveOnMouseWheel: true,
        preventDefaultMouseMove: true
      }
    ]
  }
}

function getBarOption(data, title) {
  const baseOption = getBaseOption(data, title)
  
  return {
    ...baseOption,
    xAxis: {
      type: 'category',
      data: data.map(item => item.name),
      axisLabel: {
        interval: 0,
        fontSize: isMobile.value ? 10 : 12,
        formatter: function(value) {
          return isMobile.value ? (value.length > 4 ? value.substring(0, 4) + '...' : value) : value
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: isMobile.value ? 10 : 12
      }
    },
    series: [
      {
        name: '学生人数',
        type: 'bar',
        barWidth: isMobile.value ? 12 : 20,
        barGap: 0,
        itemStyle: {
          color: '#5B8FF9'
        },
        data: data.map(item => item.count)
      }
    ]
  }
}

function getLineOption(data, title) {
  const option = getBarOption(data, title)
  option.series.forEach(series => {
    series.type = 'line'
    series.symbol = 'circle'
    series.symbolSize = isMobile.value ? 6 : 8
    series.lineStyle = {
      width: isMobile.value ? 2 : 3
    }
  })
  return option
}

function getStackOption(data, title) {
  const option = getBarOption(data, title)
  option.series[0].stack = 'total'
  
  // 添加总数显示
  option.series.push({
    name: '总数',
    type: 'bar',
    stack: 'total',
    barWidth: isMobile.value ? 12 : 20,
    itemStyle: {
      color: 'transparent'
    },
    label: {
      show: true,
      position: 'top',
      fontSize: isMobile.value ? 10 : 12,
      formatter: function(params) {
        return params.value
      }
    },
    data: data.map(item => item.count)
  })
  
  return option
}

// 响应式处理
onMounted(() => {
  const updateIsMobile = () => {
    isMobile.value = window.innerWidth < 768
  }
  window.addEventListener('resize', updateIsMobile)
  updateIsMobile()
})
</script>

<style scoped>
.student-stats-container {
  padding: 16px;
  background-color: #f7f8fa;
  border-radius: 8px;
  max-width: 100%;
  overflow-x: hidden;
}

.n-radio-group {
  margin-right: 12px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.chart-wrapper {
  width: 100%;
  margin: 0 auto;
  margin-bottom: 30px;
}

.table-area {
  width: 100%;
  margin-top: 20px;
  overflow-x: auto;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 12px 0;
}

:deep(.n-data-table) {
  border-bottom: none;
  margin-bottom: 0;
  min-width: 100%;
}

:deep(.echarts) {
  padding-bottom: 20px;
}

:deep(.echarts-slider) {
  margin-top: 15px;
}

@media (max-width: 768px) {
  .student-stats-container {
    padding: 12px;
  }
  
  .chart-wrapper {
    height: 400px;
    margin-bottom: 25px;
  }
  
  .pagination-wrapper {
    margin-top: 15px;
    padding: 8px 0;
  }
  
  :deep(.n-radio-button) {
    padding: 0 8px;
    font-size: 12px;
  }
  
  :deep(.n-data-table th),
  :deep(.n-data-table td) {
    padding: 8px 12px;
    font-size: 12px;
  }
  
  :deep(.echarts-slider-handle) {
    width: 16px !important;
    height: 20px !important;
  }
}
</style>